package com.store.app.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hyphenate.easeui.model.UserEventBean;
import com.store.app.BaseActivity;
import com.store.app.ExitApplication;
import com.store.app.LocationApplication;
import com.store.app.MainActivity;
import com.store.app.R;
import com.store.app.adapter.MemberListAdapter;
import com.store.app.bean.CreateGroupBean;
import com.store.app.bean.MemberInfoBean;
import com.store.app.http.Stores;
import com.store.app.hyphenate.Constant;
import com.store.app.imlife.activity.ChatActivity;
import com.store.app.imlife.utils.ToastTools;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.Utils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * Created by Administrator on 2016/8/31.
 * 添加群成员页面  群成员再加人 群成员减人
 */
public class AddMemberActivity extends BaseActivity implements IOnHttpListener, View.OnClickListener {
    private NetRequest netRequest;
    private ImageView public_ll_return;
    private TextView tvTitle;
    private List<MemberInfoBean> memberInfoBeanList;
    private MemberListAdapter memberListAdapter;
    private ListView listView;
    private LinearLayout public_ll_right;
    private TextView public_tv_right;
    private AlertDialog dialog;
    //type=0是创建群  type=1是群加人  type=2是群踢人
    private int type=0;
    private String groupid="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ExitApplication.getInstance().addActivity(this);
        netRequest = new NetRequest(this);
        setContentView(R.layout.activity_add_member);
        type=getIntent().getIntExtra("type", 0);
        groupid=getIntent().getStringExtra("groupid");
        initView();
        if(type==0) {
            netRequest.requestGetRelConsumerList(1, MainActivity.member_id);
        }else if(type==1) {
            netRequest.requestHXgetAddibleUsersForChatGroup(3, groupid);
            tvTitle.setText("添加联系人");
        }else if(type==2) {
            netRequest.requestHXGroupMenberList(4, groupid);
            tvTitle.setText("移除联系人");
        }
    }

    @Override
    public void onAfinalFail() {

    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        //查询会员列表
        if (requestId == 1||requestId == 3) {
            try {
                JSONObject jsonObject = new JSONObject(result);
                Map<String, String> map = Utils.getMapForJson(jsonObject.getString("doc_url"));//保存urlmap
                JSONArray jsonArray = jsonObject.getJSONArray("list");
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                    MemberInfoBean memberInfoBean = new MemberInfoBean();
                    memberInfoBean.setConsumer_id(jsonObject1.getString("consumer_id"));
                    memberInfoBean.setNick_name(jsonObject1.getString("nick_name"));
                    String pic_head = map.get(jsonObject1.getString("head_pic_path"));
                    if (TextUtils.isEmpty(pic_head)) {
                        memberInfoBean.setHead_pic_path("");
                    } else {
                        memberInfoBean.setHead_pic_path(pic_head);
                    }
                    memberInfoBean.setSelect(false);
                    memberInfoBeanList.add(memberInfoBean);
                }
                Log.v("zyl", "集合大小：" + memberInfoBeanList.size());
                memberListAdapter.notifyDataSetChanged();
            } catch (Exception e) {
            }
        }
        //创建群
        else if (requestId == 2) {
            Gson gson = new Gson();
            CreateGroupBean createGroupBean = gson.fromJson(result, CreateGroupBean.class);
            String id = createGroupBean.getId();
            if (!TextUtils.isEmpty(id)) {
                Intent intent = new Intent(this, ChatActivity.class);
                intent.putExtra("chatType", Constant.CHATTYPE_GROUP);
                intent.putExtra("userId", id);
                startActivity(intent);
                finish();
            } else {
                ToastTools.show(this, "获取不到群号", Toast.LENGTH_SHORT);
            }
        }
        //查询群成员列表 踢人
       else if (requestId == 4) {
            try {
                JSONArray jsonArray = new JSONArray(result);

                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                    if("stores".equals(jsonObject1.getString("member_type_key"))){
                        continue;
                    }
                    MemberInfoBean memberInfoBean = new MemberInfoBean();
                    memberInfoBean.setConsumer_id(jsonObject1.getString("member_id"));
                    memberInfoBean.setNick_name(jsonObject1.getString("nickname"));
                    String pic_head = jsonObject1.getString("head_pic_path");
                    if (TextUtils.isEmpty(pic_head)) {
                        memberInfoBean.setHead_pic_path("");
                    } else {
                        memberInfoBean.setHead_pic_path(pic_head);
                    }
                    memberInfoBean.setIm_user_id(jsonObject1.getString("im_user_id"));
                    memberInfoBean.setSelect(false);
                    memberInfoBeanList.add(memberInfoBean);
                }
                Log.v("zyl", "集合大小：" + memberInfoBeanList.size());
                memberListAdapter.notifyDataSetChanged();
            } catch (Exception e) {
            }
        }
        //
        else if (requestId == 5) {
            EventBus.getDefault().post(new UserEventBean("",1));
            ToastTools.show(this, "添加联系人成功！", Toast.LENGTH_SHORT);
            AddMemberActivity.this.finish();

        }
        //移除人结果
        else if (requestId == 6) {
            EventBus.getDefault().post(new UserEventBean("",1));
              ToastTools.show(this, "移除联系人成功！", Toast.LENGTH_SHORT);
              AddMemberActivity.this.finish();

        }
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        ToastTools.show(this, msg, Toast.LENGTH_SHORT);
    }

    private void initView() {
        public_ll_return = (ImageView) findViewById(R.id.public_ll_return);
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        public_ll_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tvTitle.setText("选择联系人");
        listView = (ListView) findViewById(R.id.lv_members);
        public_ll_right = (LinearLayout) findViewById(R.id.public_ll_right);
        public_ll_right.setVisibility(View.VISIBLE);
        public_ll_right.setOnClickListener(this);
        public_tv_right = (TextView) findViewById(R.id.public_tv_right);
        public_tv_right.setText("确定");
        memberInfoBeanList = new ArrayList<>();
        memberListAdapter = new MemberListAdapter(this, memberInfoBeanList);
        listView.setAdapter(memberListAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                memberInfoBeanList.get(position).setSelect(!memberInfoBeanList.get(position).isSelect());
                memberListAdapter.notifyDataSetChanged();
            }
        });
    }
    EditText addmember_edit;
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.public_ll_right:
                if(type==0) {
                    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(AddMemberActivity.this);
                    dialogBuilder.create();
                    LayoutInflater inflater = LayoutInflater.from(AddMemberActivity.this);
                    View view = inflater.inflate(R.layout.addmemberdialog, null);
                    TextView tv_cancle = (TextView) view.findViewById(R.id.balandia_cancle);
                    TextView tv_check = (TextView) view.findViewById(R.id.balandia_check);
                    addmember_edit = (EditText) view.findViewById(R.id.addmember_edit);
                    tv_cancle.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog.dismiss();
                        }
                    });
                    tv_check.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            String gropname = addmember_edit.getText().toString();
                            if (TextUtils.isEmpty(gropname)) {
                                Toast.makeText(AddMemberActivity.this, "请输入创建群的名称！", Toast.LENGTH_SHORT).show();
                                return;
                            }

                            JSONArray jsonArray = new JSONArray();
                            for (int i = 0; i < memberInfoBeanList.size(); i++) {
                                if (memberInfoBeanList.get(i).isSelect()) {
                                    try {
                                        JSONObject jsonObject = new JSONObject();
                                        jsonObject.put("member_type_key", "consumer");
                                        jsonObject.put("member_id", memberInfoBeanList.get(i).getConsumer_id() + "");
                                        jsonObject.put("nickname", memberInfoBeanList.get(i).getNick_name() + "");
                                        jsonObject.put("head_pic_path", memberInfoBeanList.get(i).getHead_pic_path() + "");
                                        jsonArray.put(jsonObject);
                                    } catch (JSONException E) {
                                    }
                                }
                            }
                            if (jsonArray.length() == 0) {
                                ToastTools.showShort(AddMemberActivity.this, "请选择联系人!");
                                dialog.dismiss();
                                return;
                            }
                            dialog.dismiss();
                            String membersInfo = jsonArray.toString();
                            Log.v("zyl", "membersInfo:" + membersInfo);
                            if (!TextUtils.isEmpty(LocationApplication.im_user_id)) {
                                netRequest.requestHXCreateChatGroupWithMembers(2, gropname, "此群由" + Stores.contact_person + "创建", LocationApplication.im_user_id, membersInfo);
                            } else {
                                ToastTools.show(AddMemberActivity.this, "请重新登录,自动激活此权限", Toast.LENGTH_SHORT);
                            }


                        }
                    });
                    dialogBuilder.setView(view);
                    dialog = dialogBuilder.show();
                }
                else if(type==1) {

                 JSONArray jsonArray = new JSONArray();
                 for (int i = 0; i < memberInfoBeanList.size(); i++) {
                     if (memberInfoBeanList.get(i).isSelect()) {
                         try {
                             JSONObject jsonObject = new JSONObject();
                             jsonObject.put("member_type_key", "consumer");
                             jsonObject.put("member_id", memberInfoBeanList.get(i).getConsumer_id() + "");
                             jsonArray.put(jsonObject);
                         } catch (JSONException E) {
                         }
                     }
                 }
                     if (jsonArray.length() == 0) {
                         ToastTools.showShort(AddMemberActivity.this, "请选择联系人!");
                         return;
                     }
                     String membersInfo = jsonArray.toString();
                     Log.v("zyl", "membersInfo:" + membersInfo);
                     if (!TextUtils.isEmpty(LocationApplication.im_user_id)) {
                         netRequest.requestHXaddBatchUsersToChatGroup(5, groupid, membersInfo);
                     } else {
                         ToastTools.show(AddMemberActivity.this, "请重新登陆,自动激活此权限", Toast.LENGTH_SHORT);
                     }




                }
                else if(type==2){


                    String membersInfo = "";
                    int member_i=0;
                    for (int i = 0; i < memberInfoBeanList.size(); i++) {
                        if (memberInfoBeanList.get(i).isSelect()) {
                            member_i+=1;
                            membersInfo+=memberInfoBeanList.get(i).getIm_user_id() + ",";

                        }
                    }
                    if (member_i == 0) {
                        ToastTools.showShort(AddMemberActivity.this, "请选择联系人!");
                        return;
                    }
                    membersInfo = membersInfo.substring(0, membersInfo.length()-1);
                    Log.v("zyl", "membersInfo:" + membersInfo);
                    if (!TextUtils.isEmpty(LocationApplication.im_user_id)) {
                        netRequest.requestHXremoveBatchUsersFromChatGroup(6, groupid, membersInfo);
                    } else {
                        ToastTools.show(AddMemberActivity.this, "请重新登陆,自动激活此权限", Toast.LENGTH_SHORT);
                    }

                }
                break;
        }
    }
}
